//
// Created by 23022 on 2022/5/11.
//

#include "medianfilter.h"
#include <bits/stdc++.h>
#include <algorithm>
#include<QDebug>

MedianFilter::MedianFilter(int size) : Filter(size) {

}

MedianFilter::~MedianFilter() {

}

Image MedianFilter::Filtering(const Image &input) {
    int height = input.Height();
    int width = input.Width();
    Image output(height,width);
    int i,j,range[4]={0},pend,x,y,place=0;
    //auto * data = new double[filterSize*filterSize];
    pend = (filterSize-1)/2;
    for(int t=0;t<3;t++)
        for (i = 0; i < height; i++)
        {
            for (j = 0; j < width; j++)
            {
                range[0] = i < pend ? 0 : (i - pend);
                range[1] = j < pend ? 0 : (j - pend);
                range[2] = (height - 1 < pend + i) ? height - 1 : (pend + i);
                range[3] = (width - 1 < pend + j) ? width - 1 : (pend + j);
                auto* data = new double[(range[2] - range[0] + 1) * (range[3] - range[1] + 1)];
                for (x = range[0]; x <= range[2]; ++x)
                    for (y = range[1]; y <= range[3]; ++y)
                        data[place++] = input.At(x, y*3+t);
                std::sort(data, data + (range[2] - range[0] + 1) * (range[3] - range[1] + 1));
                output.At(i, j*3+t) = data[(range[2] - range[0] + 1) * (range[3] - range[1] + 1) / 2];
                delete []data;
                place = 0;
            }
        }
    return output;
}
